import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

// 创建 axios 实例
const apiInstance1 = axios.create({
  baseURL: 'http://localhost:20761/', // 网关地址
  timeout: 10000, // 设置请求超时时间 10s
})

// 处理响应消息
const handleResponseMessage = (isSuc: boolean, message: string) => {
  if (isSuc == true) {
    ElMessage.success(message)
  } else {
    ElMessage.success(message)
  }
}

apiInstance1.interceptors.request.use(
  (config) => {
    const CounterStore = useCounterStore() // 每次请求时获取最新的 store
    const token = CounterStore.token // 获取 token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}` // 设置请求头
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
apiInstance1.interceptors.response.use(
  (res) => {
    handleResponseMessage(res.data.isSuc, res.data.message)
    if (!res.data.isSuc) {
      return Promise.reject(new Error(res.data.message))
    }
    return res.data
  },
  (error) => {
    const { response, message } = error
    if (response) {
      switch (response.status) {
        case 401:
          sessionStorage.removeItem('token')
          ElMessage.error('请先登录')
          window.location.href = '/' // 跳转到登录页面
          break
        default:
          console.error(`请求错误：${response.status}`)
          ElMessage.error(`请求错误：${response.status}`)
      }
    } else {
      ElMessage.error('网络连接异常' + message)
    }
    return Promise.reject(error)
  },
)

// 导出 axios 实例 default
export { apiInstance1 }
